import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class Main {
    private List<Long> times = new ArrayList<>();
    private List<Double[][]> results = new ArrayList<>();

    public static void main (String []args){
        Main test = new Main();

        MatrixGenerator MG = new MatrixGenerator();
        MG.setRandomMatrix();

        double [][] matrix1 = MG.getMatrix_M();
        double [][] matrix2 = MG.getMatrix_N();

        test.serial_matrixMultiply(matrix1,matrix2);
        System.out.println("串行计算用时 " + test.times.get(0) +"ms");

        try {
            test.parallel_matrixMultiply(matrix1,matrix2);
            System.out.println("双线程计算用时 " + test.times.get(1)+"ms");
        }catch (InterruptedException e){
            e.printStackTrace();
        }

    }

    private void serial_matrixMultiply(double[][] m, double [][] n){
        Double[][] result = new Double[m.length][n[0].length];
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < n[0].length; j++) {

                result[i][j] = 0.0;
                for (int k = 0; k < n.length; k++) {
                    result [i][j] += m[i][k] * n[k][j];
                }

            }
        }
        long endTime = System.currentTimeMillis();
        times.add(endTime-startTime);
        results.add(result);
    }

    private void parallel_matrixMultiply(double[][] m, double [][]n)throws InterruptedException{
        CountDownLatch latch = new CountDownLatch(2);
        MultiplyThread thread1 = new MultiplyThread(m,n,0,latch);
        MultiplyThread thread2 = new MultiplyThread(m,n,1,latch);
        long startTime = System.currentTimeMillis();

        thread1.start();
        thread2.start();
        latch.await();
        long endTime = System.currentTimeMillis();
        times.add(endTime-startTime);

        results.add(getResultMatrix(thread1.getResult(),thread2.getResult()));
    }
    private Double[][] getResultMatrix(double[][]m,double[][]n){
        Double [][] matrix = new Double[m.length][m[0].length];
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                matrix[i][j] = m[i][j] + n[i][j];
            }
        }
        return matrix;
    }
}
